package com.jdd.modules.parkmonthly.controller;

import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jdd.common.api.vo.Result;
import com.jdd.common.aspect.annotation.*;
import com.jdd.common.constant.JddConstant;
import com.jdd.common.system.query.QueryGenerator;
import com.jdd.common.system.vo.LoginUser;
import com.jdd.common.util.LoginUserUtils;
import com.jdd.common.util.OssUtil;
import com.jdd.common.util.SnowFlakeUtil;
import com.jdd.common.util.excel.entity.params.ExportParams;
import com.jdd.common.util.excel.entity.params.ImportParams;
import com.jdd.common.util.excel.util.ExcelImportUtil;
import com.jdd.common.util.excel.web.entity.vo.NormalExcelConstants;
import com.jdd.common.util.excel.web.view.EasypoiSingleExcelView;
import com.jdd.modules.parking.entity.ParkInfo;
import com.jdd.modules.parking.service.IParkInfoService;
import com.jdd.modules.parkmonthly.dto.MonthlyPackageInfoDTO;
import com.jdd.modules.parkmonthly.entity.MonthlyCardInfo;
import com.jdd.modules.parkmonthly.entity.MonthlyPackageInfo;
import com.jdd.modules.parkmonthly.service.IMonthlyCardInfoService;
import com.jdd.modules.parkmonthly.service.IMonthlyPackageInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @Description: 月卡车部门组织表
 * @Author: jdd
 * @Date: 2021-11-09
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "月卡车部门组织表")
@RestController
@RequestMapping("/monthlyPackageInfo")
public class MonthlyPackageInfoController {

    @Resource
    private IMonthlyPackageInfoService monthlyPackageInfoService;
    @Resource
    private IMonthlyCardInfoService monthlyCardInfoService;
    @Resource
    private OssUtil ossUtil;
    @Resource
    private IParkInfoService parkInfoService;

    /**
     * 分页列表查询
     *
     * @param monthlyPackageInfo
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "月卡套餐信息表-分页列表查询")
    @ApiOperation(value = "月卡套餐信息表-分页列表查询", notes = "月卡套餐信息表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<MonthlyPackageInfo>> queryPageList(MonthlyPackageInfo monthlyPackageInfo,
                                                           @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                           HttpServletRequest req) {
        Result<IPage<MonthlyPackageInfo>> result = new Result<IPage<MonthlyPackageInfo>>();
        Map<String, String[]> parameterMap = req.getParameterMap();
        String packageName=monthlyPackageInfo.getPackageName();
        parameterMap.put("packageName",null);
        monthlyPackageInfo.setPackageName(null);
        QueryWrapper<MonthlyPackageInfo> queryWrapper = QueryGenerator.initQueryWrapper(monthlyPackageInfo, parameterMap);
        if(StringUtils.isNotEmpty(packageName)){
            queryWrapper.lambda().like(MonthlyPackageInfo::getPackageName,packageName);
        }
        Page<MonthlyPackageInfo> page = new Page<MonthlyPackageInfo>(pageNo, pageSize);
        IPage<MonthlyPackageInfo> pageList = monthlyPackageInfoService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 上传套餐展示图片，未用到
     *
     * @param multipartFile
     * @return 阿里云图片地址
     */
    @AutoLog(value = "月卡套餐信息表-上传套餐展示图片")
    @ApiOperation(value = "月卡套餐信息表-上传套餐展示图片", notes = "月卡套餐信息表-上传套餐展示图片")
    @PostMapping(value = "/upload")
    public Result<?> upload(MultipartFile multipartFile) {
        Map<String, Object> map = new HashMap<>(16);
        Result<Object> result = new Result<>();
        try {
            String serverUrl = "";
            String[] split = serverUrl.split("\\?");
            String imgUrl = split[0];
            result.setResult(imgUrl);
            result.setSuccess(true);
        } catch (Exception exception) {
            log.error(exception.getMessage(), exception);
            result.error500("图片上传失败!");
        }
        return result;
    }

    @AutoLog(value = "车场月租套餐列表查询")
    @ApiOperation(value = "车场月租套餐列表查询",notes = "车场月租套餐列表查询")
    @GetMapping(value = "/getMonthlyPackageInfoList")
    public Result<?> getMonthlyPackageInfoList(){
        List<MonthlyPackageInfo> monthlyPackageInfoList = monthlyPackageInfoService.list();
        return Result.ok(monthlyPackageInfoList);
    }
    /**
     * /**
     *
     * @return
     * @Title: homePageParkList
     * @Description:根据登录用户绑定车场组查询车场信息
     * @author: zjf
     * @date 2021年10月27日
     * @version 1.0
     */
    @AutoLog(value = "月卡套餐信息表")
    @ApiOperation(value = "月卡套餐信息表", notes = "月卡套餐信息表")
    @GetMapping(value = "/monthlyPackageInfoList")
    public Result<?> monthlyPackageInfoList() {
        List<MonthlyPackageInfo> monthlyPackageInfoList = new ArrayList<MonthlyPackageInfo>();
        monthlyPackageInfoList = monthlyPackageInfoService.list();
        return Result.ok(monthlyPackageInfoList);
    }

    /**
     * 添加
     *
     * @param req
     * @return
     */
    @AutoLog(value = "月卡套餐信息表-添加")
    @ApiOperation(value = "月卡套餐信息表-添加", notes = "月卡套餐信息表-添加")
    @PostMapping(value = "/add")
    @OperationLogDetail(detail ="添加月卡套餐信息",level= LogLevelType.ONE,operationType = OperationType.INSERT,operationUnit = OperationUnit.UNKNOWN)
    public Result<MonthlyPackageInfo> add(HttpServletRequest req) {
        Result<MonthlyPackageInfo> result = new Result<MonthlyPackageInfo>();
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;
            MonthlyPackageInfo monthlyPackageInfo;
            try {
                Part formData = req.getPart("formData");
                InputStream inputStream = formData.getInputStream();
                String message = IoUtil.readUtf8(inputStream);
                monthlyPackageInfo = JSONObject.parseObject(message, MonthlyPackageInfo.class);
            } catch (Exception e) {
                e.printStackTrace();
                return result.error500("添加月租套餐失败");
            }
            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
            for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                MultipartFile file = entity.getValue();
                try {
                    String serverUrl = ossUtil.uploadImg2Oss(file);
                    String[] split = serverUrl.split("\\?");
                    String imgUrl = split[0];
                    monthlyPackageInfo.setImageUrl(imgUrl);
                } catch (Exception e) {
                    e.printStackTrace();
                    return result.error500("上传图片失败");
                }
            }
            monthlyPackageInfo.setId(SnowFlakeUtil.getId());
            LoginUser loginUser = LoginUserUtils.getLoginUser();
            if (null != loginUser) {
                monthlyPackageInfo.setCreateUserId(loginUser.getUsername());
                monthlyPackageInfo.setCreateUserName(loginUser.getRealname());
            }
            monthlyPackageInfo.setCreateTime(new Date());
            ParkInfo parkInfo = parkInfoService.getParkInfo();
            monthlyPackageInfo.setParkCode(parkInfo.getParkCode());
            monthlyPackageInfo.setParkName(parkInfo.getParkName());
            boolean save = monthlyPackageInfoService.save(monthlyPackageInfo);
            if (!save) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return result.error500("操作失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result.error500("操作失败");
        }
        result.success("添加成功");
        return result;
    }

    /**
     * 编辑
     *
     * @param
     * @return
     */
    @AutoLog(value = "月卡套餐信息表-编辑")
    @ApiOperation(value = "月卡套餐信息表-编辑", notes = "月卡套餐信息表-编辑")
    @OperationLogDetail(detail ="编辑月卡套餐信息",level= LogLevelType.ONE,operationType = OperationType.UPDATE,operationUnit = OperationUnit.UNKNOWN)
    @PutMapping(value = "/edit")
    public Result<MonthlyPackageInfo> edit(HttpServletRequest req) {
        Result<MonthlyPackageInfo> result = new Result<MonthlyPackageInfo>();
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;
            MonthlyPackageInfo monthlyPackageInfo;
            try {
                Part formData = req.getPart("formData");
                InputStream inputStream = formData.getInputStream();
                String message = IoUtil.readUtf8(inputStream);
                monthlyPackageInfo = JSONObject.parseObject(message, MonthlyPackageInfo.class);
//                if(StringUtils.isNotEmpty(monthlyPackageInfo.getId())){
//                    //用户进行了编辑
//                }

            } catch (Exception e) {
                e.printStackTrace();
                return result.error500("添加月租套餐失败");
            }
            if ("hasChangedImg".equals(monthlyPackageInfo.getImageUrl())) {
                //当为hasChangedImg是表示用户修改了图片
                Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
                for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                    MultipartFile file = entity.getValue();
                    try {
                        String serverUrl = ossUtil.uploadImg2Oss(file);
                        String[] split = serverUrl.split("\\?");
                        String imgUrl = split[0];
                        monthlyPackageInfo.setImageUrl(imgUrl);
                    } catch (Exception e) {
                        e.printStackTrace();
                        return result.error500("上传图片失败");
                    }
                }
            }else{
                //用户未修改图片
                monthlyPackageInfo.setImageUrl(null);
            }
            LoginUser loginUser = LoginUserUtils.getLoginUser();
            if (null != loginUser) {
                monthlyPackageInfo.setUpdateUserId(loginUser.getUsername());
                monthlyPackageInfo.setUpdateUserName(loginUser.getRealname());
            }
            monthlyPackageInfo.setUpdateTime(new Date());
            boolean update = monthlyPackageInfoService.updateById(monthlyPackageInfo);
            if (!update) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return result.error500("操作失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result.error500("操作失败");
        }
        result.success("修改成功");
        return result;
    }


    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "月卡套餐信息表-通过id删除")
    @ApiOperation(value = "月卡套餐信息表-通过id删除", notes = "月卡套餐信息表-通过id删除")
    @OperationLogDetail(detail ="删除月卡套餐信息",level= LogLevelType.ONE,operationType = OperationType.DELETE,operationUnit = OperationUnit.UNKNOWN)
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        try {
            QueryWrapper<MonthlyCardInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("package_id", id);
            queryWrapper.ne("monthly_status", JddConstant.IntNumber.INT_THREE);
            Integer count = monthlyCardInfoService.count(queryWrapper);
            if (count > JddConstant.IntNumber.INT_ZERO) {
                return Result.error("该套餐关联了在用的月卡信息，不允许删除");
            }
            monthlyPackageInfoService.removeById(id);
        } catch (Exception e) {
            log.error("删除失败", e.getMessage());
            return Result.error("删除失败!");
        }
        return Result.ok("删除成功!");
    }


    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "月卡套餐信息表-通过id查询")
    @ApiOperation(value = "月卡套餐信息表-通过id查询", notes = "月卡套餐信息表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<MonthlyPackageInfo> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<MonthlyPackageInfo> result = new Result<MonthlyPackageInfo>();
        MonthlyPackageInfo monthlyPackageInfo = monthlyPackageInfoService.getById(id);
        if (monthlyPackageInfo == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(monthlyPackageInfo);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response, MonthlyPackageInfo
            monthlyPackageInfo) {
        // Step.1 组装查询条件
        QueryWrapper<MonthlyPackageInfo> queryWrapper = QueryGenerator.initQueryWrapper(monthlyPackageInfo, request.getParameterMap());
        ParkInfo parkInfo = parkInfoService.getParkInfo();
       	queryWrapper.eq("park_code",parkInfo.getParkCode());
        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new EasypoiSingleExcelView());
        List<MonthlyPackageInfo> pageList = monthlyPackageInfoService.list(queryWrapper);
        List<MonthlyPackageInfoDTO> list = new ArrayList<>();
        for(MonthlyPackageInfo monthlyPackageInfo1:pageList){
            //翻译
            monthlyPackageInfoService.translateMonthlyPackageInfo(monthlyPackageInfo1,list);
        }
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "月卡套餐信息");
        mv.addObject(NormalExcelConstants.CLASS, MonthlyPackageInfoDTO.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("月卡套餐信息", "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, list);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = ImportParams.builder().build();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<MonthlyPackageInfo> listMonthlyPackageInfos = ExcelImportUtil.importExcel(file.getInputStream(), MonthlyPackageInfo.class, params);
                monthlyPackageInfoService.saveBatch(listMonthlyPackageInfos);
                return Result.ok("文件导入成功！数据行数:" + listMonthlyPackageInfos.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "月卡套餐信息表-批量删除")
    @ApiOperation(value = "月卡套餐信息表-批量删除", notes = "月卡套餐信息表-批量删除")
    @OperationLogDetail(detail ="批量删除月卡套餐信息",level= LogLevelType.ONE,operationType = OperationType.DELETE,operationUnit = OperationUnit.UNKNOWN)
    @DeleteMapping(value = "/deleteBatch")
    public Result<MonthlyPackageInfo> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<MonthlyPackageInfo> result = new Result<>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            List<String> idList = Arrays.asList(ids.split(","));
            for(String id:idList){
                //判断当前套餐下是否关联了月租信息
                LambdaQueryWrapper<MonthlyCardInfo> wrapper=new LambdaQueryWrapper<>();
                wrapper.eq(MonthlyCardInfo::getPackageId,id);
                List<MonthlyCardInfo> list = monthlyCardInfoService.list(wrapper);
                if(CollectionUtils.isNotEmpty(list)){
                    //关联了月租信息
                    log.info("id为{}的套餐中关联了月租信息，不允许删除",id);
                    continue;
                }
                monthlyPackageInfoService.removeById(id);
            }
            result.success("删除成功!");
        }
        return result;
    }

}
